/**
 * AssistantSelector - Dropdown Assistant Selector Component
 * 
 * A compact dropdown selector for choosing assistants in various contexts
 * (e.g., in chat header, settings, etc.)
 */

import { useState, useEffect } from 'react';
import { Check, ChevronsUpDown, Bot } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from '@/components/ui/command';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover';
import { cn } from '@/lib/utils';
import type { Assistant } from './AssistantCard';

interface AssistantSelectorProps {
  selectedId?: string | null;
  onSelect?: (assistant: Assistant | null) => void;
  placeholder?: string;
  className?: string;
}

export function AssistantSelector({
  selectedId,
  onSelect,
  placeholder = '选择助手',
  className,
}: AssistantSelectorProps) {
  const [open, setOpen] = useState(false);
  const [assistants, setAssistants] = useState<Assistant[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchAssistants();
  }, []);

  const fetchAssistants = async () => {
    try {
      setLoading(true);
      const response = await fetch('http://localhost:3000/api/subagents');
      const data = await response.json();
      if (data.success) {
        setAssistants(data.data.subagents || []);
      }
    } catch (error) {
      console.error('Failed to fetch assistants:', error);
    } finally {
      setLoading(false);
    }
  };

  const selectedAssistant = selectedId
    ? assistants.find(a => a.id === selectedId)
    : null;

  // Group assistants by category
  const groupedAssistants = assistants.reduce((acc, assistant) => {
    const category = assistant.category || 'other';
    if (!acc[category]) {
      acc[category] = [];
    }
    acc[category].push(assistant);
    return acc;
  }, {} as Record<string, Assistant[]>);

  const categoryLabels: Record<string, string> = {
    development: '开发',
    testing: '测试',
    security: '安全',
    documentation: '文档',
    database: '数据库',
    analysis: '分析',
    devops: 'DevOps',
    design: '设计',
    other: '其他',
  };

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <Button
          variant="outline"
          role="combobox"
          aria-expanded={open}
          className={cn('justify-between', className)}
        >
          <div className="flex items-center gap-2 truncate">
            <Bot className="w-4 h-4 flex-shrink-0" />
            <span className="truncate">
              {selectedAssistant ? selectedAssistant.name : placeholder}
            </span>
          </div>
          <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
        </Button>
      </PopoverTrigger>
      <PopoverContent className="w-[300px] p-0">
        <Command>
          <CommandInput placeholder="搜索助手..." />
          <CommandList>
            <CommandEmpty>
              {loading ? '加载中...' : '未找到助手'}
            </CommandEmpty>

            {/* Default Assistant */}
            <CommandGroup heading="默认">
              <CommandItem
                value="default"
                onSelect={() => {
                  onSelect?.(null);
                  setOpen(false);
                }}
              >
                <Check
                  className={cn(
                    'mr-2 h-4 w-4',
                    !selectedId ? 'opacity-100' : 'opacity-0'
                  )}
                />
                <Bot className="mr-2 h-4 w-4" />
                通用助手
              </CommandItem>
            </CommandGroup>

            {/* Grouped Assistants */}
            {Object.entries(groupedAssistants).map(([category, items]) => (
              <CommandGroup 
                key={category} 
                heading={categoryLabels[category] || category}
              >
                {items.map((assistant) => (
                  <CommandItem
                    key={assistant.id}
                    value={assistant.id}
                    onSelect={() => {
                      onSelect?.(assistant);
                      setOpen(false);
                    }}
                  >
                    <Check
                      className={cn(
                        'mr-2 h-4 w-4',
                        selectedId === assistant.id ? 'opacity-100' : 'opacity-0'
                      )}
                    />
                    <Bot className="mr-2 h-4 w-4" />
                    <div className="flex-1 truncate">
                      <div className="font-medium truncate">{assistant.name}</div>
                      <div className="text-xs text-muted-foreground truncate">
                        {assistant.description}
                      </div>
                    </div>
                  </CommandItem>
                ))}
              </CommandGroup>
            ))}
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover>
  );
}

